package com.cupdata.zicon.thrift.config;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class ThriftApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

	private Logger log = LoggerFactory.getLogger(ThriftServerAutoConfiguration.class);
	
	@Autowired
	private TMultiplexedProcessor tMultiplexedProcessor;
	
	@Value("${eureka.instance.metadata-map.port:0}")
	int thriftServerPort;
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if(thriftServerPort == 0){
			return;
		}
		try {
			final TServer server = new TThreadPoolServer(new TThreadPoolServer.Args(
					 new TServerSocket(thriftServerPort)).processor(tMultiplexedProcessor));
			
			ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
			executor.execute(new Runnable() {
				@Override
				public void run() {
					server.serve();	
				}
			});
			log.info("Thrift Server Start port is " + thriftServerPort);
		} catch (TTransportException e) {
			e.printStackTrace();
		} 
      }
	

}
